package edu.suda.basic;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapTest
{
	public static String getKeyByValue(Map<String, String> map, Object value)
	{
		String keys = "";
		Iterator<?> it = map.entrySet().iterator();
		while (it.hasNext())
		{
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Entry) it.next();
			Object obj = entry.getValue();
			if (obj != null && obj.equals(value))
			{
				keys = (String) entry.getKey();
			}
		}
		return keys;
	}

	public static void main(String[] args)
	{
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("username", "zhaokuo");
		map.put("password", "123456");
		map.put("email", "zhaokuo719@163.com");
		map.put("sex", "男");

		// 第一种 用for循环的方式
		for (Map.Entry<String, String> m : map.entrySet())
		{
			System.out.println(m.getKey() + "\t" + m.getValue());
		}

		// 利用迭代 （Iterator）
		Set<Entry<String,String>> set = map.entrySet();
		Iterator<Entry<String,String>> iterator = set.iterator();
		while (iterator.hasNext())
		{
			Map.Entry<String, String> enter = (Entry<String, String>) iterator.next();
			System.out.println(enter.getKey() + "\t" + enter.getValue());
		}
		// 利用KeySet 迭代
		Iterator<String> it = map.keySet().iterator();
		while (it.hasNext())
		{
			String key;
			String value;
			key = it.next().toString();
			value = (String) map.get(key);
			System.out.println(key + "--" + value);
		}
		// 利用EnterySet迭代
		Iterator<Entry<String,String>> i = map.entrySet().iterator();
		System.out.println(map.entrySet().size());
		String key;
		String value;
		while (i.hasNext())
		{
			@SuppressWarnings("rawtypes")
			Map.Entry entry = (Map.Entry) i.next();
			key = entry.getKey().toString();
			value = entry.getValue().toString();
			System.out.println(key + "====" + value);
		}

		System.out.println(getKeyByValue(map, "zhaokuo"));		
	}
}
